﻿using System.Windows;
using System.Windows.Navigation;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Phone.Controls;
using Tfs.OnTheRoad.Pages;
using Tfs.OnTheRoad.ViewModel;
using System;
namespace Tfs.OnTheRoad
{
    public partial class MainPage : BasePage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();  
        }

        bool firstTime = true;
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //We set it to -1 to avoid that the selectionChanged event is not being triggered if we are coming back
            //to this page(back button)
            ItemsListBox.SelectedIndex = -1;            

            //Nop settings defined?? We need to define it first!
            if (!App.SettingsViewModel.CanTest)
            {
                //Quit the app since the guy just hit the Back Button
                if (!firstTime)
                    App.Quit();
                firstTime = false;
                MessageBox.Show("Welcome to TFS On The Road. In order to use the application you need to provide the access settings on the next screen. If you have questions please click on the 'More Information' button", "Welcome", MessageBoxButton.OK);
                Commands.NavigateToSettingsCommand cmd = new Commands.NavigateToSettingsCommand();
                cmd.Execute(null);
                return;
            }            

            var loadedViewModel = this.DataContext as ProjectListViewModel;
            //// If viewModel is not null it means that the user navigated back to this page and the viewModel is already loaded.
            if (loadedViewModel == null)
            {
                loadedViewModel = new ProjectListViewModel();
                this.DataContext = loadedViewModel;
                Messenger.Default.Send<PhoneApplicationPage>(this, "RestoreState");   
                loadedViewModel.LoadData();
                
            }
            profileListPicker.SelectedItem = App.SettingsViewModel;
        }
    }
}